package com.qf.controller;


import com.qf.annotation.ProccessInfo;
import com.qf.commons.TableData;
import com.qf.entity.User;
import com.qf.exception.BizException;
import com.qf.exception.ControllerException;
import com.qf.service.UserService;
import com.qf.utils.DateUtils;
import com.qf.utils.StringUtils;
import org.apache.log4j.Logger;
import org.jctools.maps.NonBlockingHashMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin("*")
@RestController
@RequestMapping("/user")
public class UserController {

    @Value("${excelPath}")
    private  String excelPath;

    private Logger logger = Logger.getLogger(UserController.class);

    @Value("${fileUplaodLocation}")
    private String fileUplaodLocation;

//    @Value("${imageServer}")
//    private String imageServer;

    private UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    // 获取分页数据
    @GetMapping
    public Object getPageData(@RequestParam(defaultValue = "0") Integer offset,
                              @RequestParam(defaultValue = "10") Integer limit,
                              String name, String sex, Integer status,String email,
                             @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date afterDate,
                              @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endDate) {
        System.out.println("name:"+name+"\tsex:"+sex+"\temail:"+email+"\tafterDateStr:"+afterDate+"\tstatus:"+status+"\tendDateStr:"+endDate);

        if (!"F".equals(sex)&&!"M".equals(sex)){
            sex=null;
        }

//        Date afterDate =null;
//        Date endDate =null;
//        if (afterDateStr!=null){
//         afterDate =DateUtils.strToDate(afterDateStr,DateUtils.DATE_FULL_STR);
//        }
//        if (endDateStr!=null){
//            endDate =DateUtils.strToDate(afterDateStr,DateUtils.DATE_FULL_STR);
//        }


        logger.info("查询用户分页信息");
        TableData<User> tableData = null;
        try {
            tableData = userService.getPageData(offset, limit,"%"+ name+"%", sex, status,
                     email, afterDate,endDate);
        } catch (BizException e) {
           throw e;
        } catch (Exception ex) {
            throw new ControllerException("控制层异常: " + ex.getMessage());
        }
        return tableData;
    }

    /**
     * 400: 1.表示缺少参数; 2.参数类型错误。
     */
    // http://localhost:8081/ssm_war_exploded/user/45
    @ProccessInfo(value = "删除用户", requireParamInfo = true)
    @DeleteMapping("/{id}")
    public Object delete(@PathVariable("id") Integer id) {
        Map<String, Object> map = new HashMap<>();
        try {
//            Integer.parseInt("abc");
            userService.deleteUserById(id);
            map.put("code", 1);
            map.put("msg", "success");
        } catch (BizException e) {
            throw e;
        } catch (Exception ex) {
            throw new ControllerException("控制层异常: " + ex.getMessage());
        }
        return map;
    }


   // @GetMapping("/{id}")
    public Object getById(@PathVariable("id") Integer id) {

        User user = null;
        try {
//            String st = null;
//            st.startsWith("abc");
            user = userService.getUserById(id);
        } catch (BizException e) {
            throw e;
        } catch (Exception ex) {
            throw new ControllerException("控制层异常: " + ex.getMessage());
        }
        return user;
    }

    // 更新用户
    @ProccessInfo(value = "后台管理人员更新用户信息", requireParamInfo = true)
    @PutMapping
    public Object updateUser(User user) {
        Map<String, Object> map = new HashMap<>();
        try {
            userService.updateUser(user);
            map.put("code", 1);
            map.put("msg", "success");
        } catch (BizException e) {
            throw e;
        } catch (Exception ex) {
            throw new ControllerException("控制层异常: " + ex.getMessage());
        }
        return map;
    }

    @ProccessInfo("上传用户头像")
    @PostMapping("/upload")
    public Object uploadAvatar(MultipartFile avatar) {
        // 获取文件的原始名字
        String originFileName = avatar.getOriginalFilename();

        // 获取文件的后缀： .png .jpg XXXX
        String fileSuffix = originFileName.substring(originFileName.lastIndexOf("."));

        // 新的文件名
        String newFileName = System.nanoTime() + StringUtils.generateRandomString(10) + fileSuffix;

        try {
            avatar.transferTo(new File(fileUplaodLocation + newFileName));  // D:/nginx-server/images/8877776656afeji786766.png
        } catch (IOException ioException) {
           throw new ControllerException(ioException.getMessage());
        }

        Map<String, String> map = new HashMap<>();
        map.put("avatar", newFileName);

        return map; // http://localhost/8877776656afeji786766.png
    }
    @ProccessInfo(value = "后台管理人员导出Excel文件", requireParamInfo = true)
    @GetMapping("/download")
    public void downloadExcel(HttpServletResponse response,@RequestParam(value = "name") String name, String sex, Integer status,String email,
                              @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date afterDate,
                              @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endDate) {
        System.out.println("name:"+name);
        if (!"F".equals(sex)&&!"M".equals(sex)){
            sex=null;
        }
        try {
            //根据时间生成文件名  20200630164834.xls
            String fileName = DateUtils.transferDateToStr(new Date(), DateUtils.DATE_KEY_STR) + ".xls";
            String fullPath = userService.generateExcel(fileName,"%"+ name+"%",  sex,  status, email,afterDate,endDate);


            fileName = URLEncoder.encode(fileName, "utf-8");

            response.setHeader("content-disposition", "attachment;filename=" + fileName);

            FileCopyUtils.copy(new FileInputStream(fullPath), response.getOutputStream());
        } catch (BizException e) {
            throw e;
        } catch (Exception ex) {
            throw new ControllerException("控制层异常: " + ex.getMessage());
        }
    }

    @ProccessInfo(value = "后台管理人员导入Excel文件", requireParamInfo = true)
    @PostMapping("/uploadExcel")

    public Object uploadExcel(MultipartFile excel) {
        Integer num = 0;
        try {
            InputStream is = excel.getInputStream();  //获取输入流
            num = userService.parseExcelAndInsertData(is);
        } catch (BizException bizException) {
            throw bizException;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new ControllerException("控制层上传Excel异常: " + ex.getMessage());
        }
        if (num>0){
            return dataMap(1,"导入成功");
        }else {
            return dataMap(0,"导入失败");
        }

    }

    @GetMapping("/excelmodel")
    public void getExcelModel(HttpServletResponse response){
        try {
            String   fileName = URLEncoder.encode("userExcelModel.xls", "utf-8");

            response.setHeader("content-disposition", "attachment;filename=" + fileName);
            FileCopyUtils.copy(new FileInputStream(excelPath+"userExcelModel.xls"),
                    response.getOutputStream());
        } catch (IOException e) {
            throw new ControllerException("控制层下载excel文件错误");
        }
    }


    public NonBlockingHashMap<String, Object> dataMap(Integer num, String msg) {
        NonBlockingHashMap<String, Object> map =
                new NonBlockingHashMap<>();

        map.put("code",num);
        map.put("msg",msg);

        return map;
    }

}
